<script setup lang="ts">
import { ref, onUnmounted } from 'vue'
import { showToast, type FormInstance, showSuccessToast } from 'vant'
import { mobileRules, passwordRules, codeRules } from '@/utils/rules'
import { MobileByPassword, MobileByCode, MobileByLogin } from '@/services/user'
import { useUserStore } from '@/stores'
import { useRoute, useRouter } from 'vue-router'
// route当前路由对象
const route = useRoute()
// router操作所有的路由对象
const router = useRouter()

const store = useUserStore()
const agree = ref(false)

// 是否是密码登陆
const isPass = ref(true)
// 小眼睛是否打开
const show = ref(false)
const mobile = ref('')
const password = ref('')
const code = ref('')
const form = ref<FormInstance | null>(null)
// 倒计时的计数器
let timer = ref(0)
let timeId: number
// 实现登陆功能
const login = async () => {
  if (!agree.value) return showToast('请勾选协议！')
  // 校验通过，发送请求，实现登陆
  const res = isPass.value
    ? await MobileByPassword(mobile.value, password.value)
    : await MobileByLogin(mobile.value, code.value)
  console.log(res.data)
  // 存储到pinia里面
  store.setUserInfo(res.data)
  // 跳转页面   用户中心/user
  router.push((route.query.returnUrl as string) || '/user')
}

const sendCode = async () => {
  if (timer.value > 0) return // 计数器大于0 60s之内不再重复发送请求
  // 通过表单对象.value.validate('name属性值') 对单个表单进行校验，返回值一个promise实例
  await form.value?.validate('mobile')
  // 手机号验证通过，发送请求，获取短信验证码
  const res = await MobileByCode(mobile.value, 'login')
  console.log(res, 'res.data.code as string')
  showSuccessToast(`发送短信验证码成功！:${res.data.code}`)
  // 计时器值修改为 60
  timer.value = 60
  // 开启定时器,如果保证同时只开启一个定时器
  clearInterval(timeId)
  timeId = setInterval(() => {
    // 计数器减一
    timer.value--
    // 如果计算器 小于或者等于0 关闭定时器
    if (timer.value <= 0) {
      clearInterval(timeId)
    }
  }, 1000)
}

// 组件卸载时清除定时器
onUnmounted(() => {
  clearInterval(timeId)
})
</script>
<template>
  <div class="login-page">
    <CpNavBar
      right-text="注册"
      @on-click-right="$router.push('/register')"
    ></CpNavBar>
    <div class="login-head">
      <h3>{{ isPass ? '密码登录' : '短信验证码登陆' }}</h3>
      <a href="javascript:;" @click="isPass = !isPass">
        <span>{{ isPass ? '短信验证码登录' : '密码登陆' }}</span>
        <van-icon name="arrow"></van-icon>
      </a>
    </div>
    <!-- form 表单 -->
    <!-- button按钮上 加上 native-type="submit" 可以自动触发整个表单的校验，
      只有表单校验都通过了才会执行van-form上的submit事件对应的回调函数
    -->
    <van-form @submit="login" ref="form">
      <van-field
        name="mobile"
        placeholder="请输入手机号"
        v-model="mobile"
        type="tel"
        :rules="mobileRules"
      ></van-field>
      <!-- 密码登陆 -->
      <van-field
        v-if="isPass"
        :rules="passwordRules"
        placeholder="请输入密码"
        v-model="password"
        :type="show ? 'text' : 'password'"
      >
        <template #button>
          <CpIcon
            @click="show = !show"
            :name="`login-eye-${show ? 'on' : 'off'}`"
          ></CpIcon>
        </template>
      </van-field>
      <!-- 短信验证码登陆 -->
      <van-field
        v-else
        v-model="code"
        placeholder="请输入验证码"
        :rules="codeRules"
      >
        <template #button>
          <span
            class="btn-send"
            :class="{ active: timer > 0 }"
            @click="sendCode"
            >{{ timer > 0 ? `${timer}s再发送验证码` : '发送验证码' }}</span
          >
        </template>
      </van-field>
      <!-- 用户协议 -->
      <div class="cp-cell">
        <van-checkbox v-model="agree">
          <span>我已同意</span>
          <a href="javascript:;">用户协议</a>
          <span>及</span>
          <a href="javascript:;">隐私条款</a>
        </van-checkbox>
      </div>
      <div class="cp-cell">
        <van-button block round type="primary" native-type="submit"
          >登 录</van-button
        >
      </div>
      <div class="cp-cell">
        <a href="javascript:;">忘记密码？</a>
      </div>
    </van-form>

    <!-- 第三方登陆 -->
    <div class="login-other">
      <van-divider>第三方登录</van-divider>
      <div class="icon">
        <img src="@/assets/qq.svg" alt="" />
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.login {
  &-page {
    padding-top: 46px;
  }
  &-head {
    padding: 30px 30px 50px;
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    line-height: 1;
    h3 {
      font-weight: normal;
      font-size: 24px;
    }
    a {
      font-size: 15px;
    }
  }
  &-other {
    margin-top: 60px;
    padding: 0 30px;
    .icon {
      display: flex;
      justify-content: center;
      img {
        width: 36px;
        height: 36px;
        padding: 4px;
      }
    }
  }
}

.van-form {
  padding: 0 14px;
  .cp-cell {
    height: 52px;
    line-height: 24px;
    padding: 14px 16px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    .van-checkbox {
      a {
        color: var(--cp-primary);
        padding: 0 5px;
      }
    }
  }
  // van-form 下添加
  .btn-send {
    color: var(--cp-primary);
    &.active {
      color: rgba(22, 194, 163, 0.5);
    }
  }
}
</style>
